package com.lei.springbootpractice.controller;

import com.lei.springbootpractice.pojo.AddressPojo;
import com.lei.springbootpractice.service.AddressService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/address")
public class AddressController {
    private static final Logger logger = LoggerFactory.getLogger(AddressController.class);

    @Autowired
    AddressService addressService;

    // 修改：使用HttpSession替代Principal
    @GetMapping("/list")
    public String getAddresses(HttpSession session, Model model) {
        String userId = (String) session.getAttribute("loggedInUser");
        if (userId == null) {
            return "redirect:/login";   // 会话中无用户信息，重定向到登录页面
        }
        logger.info("当前用户ID: {}", userId);
        List<AddressPojo> addresses = addressService.getAddressesByUserId(userId);

        // 详细日志输出
        logger.info("查询到的地址数量: {}", addresses.size());
        for (AddressPojo address : addresses) {
            logger.info("地址详情 - ID: {}, 用户ID: {}, 地址内容: {}, 用户名: {}, 电话: {}",
                address.getAddressId(), address.getUserId(), address.getAddress(),
                address.getUsername(), address.getPhone());
        }

        model.addAttribute("addresses", addresses);
        model.addAttribute("userId", userId);
        logger.info("传递给前端的userId: {}", userId);
        return "customer/address-list";
    }

    // 修改：使用HttpSession替代Principal
    @PostMapping("/add")
    @ResponseBody
    public Map<String, Object> addAddress(HttpSession session, @RequestBody AddressPojo address) {
        Map<String, Object> response = new HashMap<>();
        if (address == null || address.getAddress() == null || address.getAddress().trim().isEmpty()) {
            response.put("success", false);
            response.put("message", "地址信息不能为空");
            return response;
        }
        // 从会话中获取用户ID
        String userId = (String) session.getAttribute("loggedInUser");
        if (userId != null && (address.getUserId() == null || address.getUserId().isEmpty())) {
            address.setUserId(userId);
        }

        AddressPojo savedAddress = addressService.addAddress(address);
        if (savedAddress != null && savedAddress.getAddressId() != null) {
            response.put("success", true);
            response.put("data", savedAddress);
            response.put("message", "地址添加成功");
        } else {
            response.put("success", false);
            response.put("message", "地址添加失败");
        }
        return response;
    }

    @PostMapping("/update")
    @ResponseBody
    public boolean updateAddress(@RequestBody AddressPojo address) {   // 接收完整的地址对象
        System.out.println("更新地址: " + address); // 调试日志
        if (address == null || address.getAddress() == null || address.getAddress().trim().isEmpty()) {
            return false;
        }
        return addressService.updateAddress(address);
    }

    @PostMapping("/delete")
    @ResponseBody
    public Map<String, Object> deleteAddress(@RequestParam String addressId) {
        System.out.println("删除地址ID: " + addressId);
        Map<String, Object> response = new HashMap<>();

        if (addressId == null || addressId.trim().isEmpty()) {
            response.put("success", false);
            response.put("message", "地址ID不能为空");
            return response;
        }

        try {
            boolean result = addressService.deleteAddress(addressId);
            response.put("success", result);
            response.put("message", result ? "删除成功" : "删除失败");
            return response;
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "删除时发生错误: " + e.getMessage());
            return response;
        }
    }

    @GetMapping("/detail")
    @ResponseBody
    public Map<String, Object> getAddress(@RequestParam String addressId) {
        Map<String, Object> response = new HashMap<>();
        try {
            AddressPojo address = addressService.getAddressById(addressId);
            if (address == null || address.getAddressId() == null) {
                response.put("success", false);
                response.put("message", "地址不存在");
            } else {
                response.put("success", true);
                response.put("data", address);
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取地址详情失败: " + e.getMessage());
        }
        return response;
    }

    @GetMapping("/api/{userId}")
    @ResponseBody
    public List<AddressPojo> getUserAddresses(@PathVariable String userId) {
        logger.info("获取用户地址列表，用户ID: {}", userId);
        List<AddressPojo> addresses = addressService.getAddressesByUserId(userId);
        logger.info("找到地址数量: {}", addresses.size());
        return addresses;
    }
}
